//
//  YXYHomeController.swift
//  SinaWeibo
//
//  Created by 袁向阳 on 16/6/23.
//  Copyright © 2016年 YXY.cn. All rights reserved.
//

import UIKit

private let HomeCellReuseId : String = "HomeCellReuseId"

class YXYHomeController: YXYBaseTableController {
    
    // 数据数组
    var dataArray: [YXYStatus] = [YXYStatus]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin {
            visitorView.visitorViewSetUI(nil, message: nil)
            return
        }
        
        // 注册cell
        tableView.registerClass(YXYStatusCell.self, forCellReuseIdentifier: HomeCellReuseId)
        
        // 添加子控件
        setUpUI()
        
        // 获取微博数据
        loadData(pullUpView.isAnimating())
        
        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableViewAutomaticDimension
        
        self.tableView.separatorStyle = .None
    }
    
//    override func viewDidAppear(animated: Bool) {
//        refreshView.startRefreshing()
//        
//    }
    
    // MARK: - 添加子控件
    private func setUpUI () {
        // 添加遮盖视图
        addCoverView()
        // 添加上提加载更多
        tableView.tableFooterView = pullUpView
        // 添加下拉刷新
        tableView.addSubview(refreshView)
        
    }
    
    // MARK: - 遮盖视图
    private func addCoverView () {
        navigationController?.view.addSubview(coverView)
        coverView.addSubview(warningImg)
        warningImg.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(coverView)
            make.size.equalTo(CGSize(width: kWidth, height: kHeight-108))
        }
    }
    
    // 遮盖视图
    lazy var coverView: UIView = {
        let coverView = UIView(frame: CGRect(x: 0, y: 64, width: kWidth, height: kHeight-108))
        coverView.backgroundColor = UIColor(red: 237/255.0, green: 237/255.0, blue: 237/255.0, alpha: 1.0)
        return coverView
    }()
    // 遮盖视图上的提示语
    lazy var warningImg: UIImageView = {
        let img = UIImageView(image: UIImage(named: "1024的图片"))
        return img
    }()
    
    // 上提加载更多的控件
    lazy var pullUpView: UIActivityIndicatorView = {
        let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        activity.color = themeColor
        return activity
    }()
    // 下拉刷新控件
    lazy var refreshView: YXYRefreshControl = {
        let refresh = YXYRefreshControl()
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
        refresh.backgroundColor = themeColor
        return refresh
    }()
    
    // MARK: - 下拉刷新的方法
    @objc private func refreshAction () {
        loadData(pullUpView.isAnimating())
    }
    
    
    /// 获取网络微博数据
    func loadData (isAnimating: Bool) {
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        
        // 上提加载更多
        if isAnimating {
            
            maxId = dataArray.last?.id ?? 0
            
        }else {
            // 下拉刷新
            sinceId = dataArray.first?.id ?? 0
        }
        
        YXYNetWorkTool.sharedWorkTool.loadStatusData(sinceId, max_Id: maxId, success: { (response) -> () in
            
            // 停止动画
            self.endRefreshing()
            
            // 判断是否有值  且是否是字典数组类型
            guard let res = response?["statuses"] as? [[String: AnyObject]] else {
                return
            }
            
            // 遍历数组，字典转模型
            var tempArray: [YXYStatus] = [YXYStatus]()
            
            for dict in res {
                let status = YXYStatus(dict: dict)
                tempArray.append(status)
            }
            
            // 上提加载更多
            if maxId > 0 {
                tempArray.removeFirst()
                self.dataArray = self.dataArray + tempArray
            }else {
                self.dataArray = tempArray + self.dataArray
            }
            
            // 去掉遮盖视图
            if self.coverView.alpha != 0 {
                self.coverView.alpha = 0
                self.coverView.removeFromSuperview()
            }
            
            self.tableView.reloadData()
            
            }, failure: { (error) -> () in
                
                print(error?.description)
                
        })
    }
    
    // MARK: - 停止动画
    private func endRefreshing() {
        pullUpView.stopAnimating()
        refreshView.endRefreshing()
    }
}


// MARK: - 数据源方法
extension YXYHomeController {
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellReuseId, forIndexPath: indexPath) as! YXYStatusCell
        
        cell.status = self.dataArray[indexPath.row]
        
        return cell
        
    }
}

// MARK: - tableView代理方法
extension YXYHomeController {
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.row == dataArray.count - 1 && !pullUpView.isAnimating() {
            pullUpView.startAnimating()
            
            loadData(pullUpView.isAnimating())
        }
        
    }
}
